<?php

include '../config/config.php';

$server = new Swoole\WebSocket\Server(WEBSOCKET_IP, WEBSOCKET_PORT);

$server->set([
    //websocket客户端心跳检测(可关闭心跳检测)
    'heartbeat_idle_time' => HEARTBEAT_IDLE_TIME,
    'heartbeat_check_interval' => HEARTBEAT_CHECK_INTERVAL,
]);

//你的redis配置
$redis = new Redis();
$redis->connect(REDIS_IP, REDIS_PORT);
$redis->auth(REDIS_PASSWORD);

$server->on('start', function ($server) {
    echo 'websocket-server is running on 127.0.0.1:' . WEBSOCKET_PORT . "\n";
});

$server->on('open', function (Swoole\WebSocket\Server $server, $request) use ($redis) {
    echo "客户端:{$request->fd}连接成功\n";
});

$server->on('message', function (Swoole\WebSocket\Server $server, $frame) use ($redis) {
    echo "接受来自{$frame->fd}客户端,数据为:{$frame->data},opcode:{$frame->opcode}\n";
    $message = json_decode($frame->data, true);

    //websocket客户端自定义名称加入redis的liveset集合中,并绑定
    if (isset($message['identity'])) {
        $identity = $message['identity'];
        $redis->sAdd('liveset', $frame->fd . '-' . $identity);
    }

    //此处可开启鉴权
    // if($message->token != 'aaa' || $message->event != 'aaa'){
    //       $server->disconnect($frame->fd,$code = 1000,$reason = "身份信息不明");
    //}

});

//关闭websocket客户端
$server->on('close', function ($ser, $fd) use ($redis) {
    echo "客户端{$fd}已关闭\n";
    //获取在线所有成员
    $liveset = $redis->sMembers('liveset');
    $array = [];
    foreach ($liveset as $v) {
        $middle = explode('-', $v);
        $array[$middle[0]] = $middle[1];
    }
    if (array_key_exists($fd, $array)) {
        $redis->sRem('liveset', $fd . '-' . $array[$fd]);
    }
});

//http-server
//websocket客户端连接到websocket服务,之后前端通过http协议,触发此方法,遍历当前选择的在线的websocket客户端,将http协议的数据通过websocket形式发出去

$server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) use ($redis) {

    global $server;

    if ($request->server['request_uri'] == '/favicon.ico') {
        $response->status(404);
        $response->end();
        return;
    }

    $message = isset($request->get['message']) ? $request->get['message'] : '';
    $choose = isset($request->get['choose']) ? $request->get['choose'] : 'all';
    if (empty($message)) {
        $response->write('Request parameter error');
    }

    if ($choose == 'all') {
        //通过http发送消息给所有websocket客户
        foreach ($server->connections as $fd) {
            $status = $server->connection_info($fd)['websocket_status'];
            if ($status != 0) {
                $server->push($fd, $message);
            }
        }
        $response->write('Push all success');
    } else {
        //通过http发送消息给指定的打印机
        $liveset = $redis->sMembers('liveset');
        foreach ($liveset as $v) {
            $middle = explode('-', $v);
            $key = array_search($choose, $middle);
            if ($key == 1) {
                $server->push($middle[0], $message);
            }
        }
        $response->write('Push success');
    }
    $response->end();
});

$server->start();
